package com.jams.goodox.activity.serve.visitor;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hangzhou.jin.customview.TextMoreLayout;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.activity.serve.ServeStopTime;
import com.jams.goodox.entity.User;
import com.jams.goodox.entity.VisitorEwmBean;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.ServiceService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;
import com.jams.goodox.widget.EditTextWithDel;
import com.jams.goodox.widget.NumberPickerDialog;
import com.jams.library.widget.switch_button.SwitchButton;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 访客通行页
 * Created by jams_zhen on 2016/9/26.
 */

public class VisitorAddActivity extends BaseActivity implements NumberPickerDialog.OnNumberPickerClick{
    @Bind(R.id.tx_userName)
    TextView txUserName;
    @Bind(R.id.tx_userTel)
    TextView txUserTel;
    @Bind(R.id.tx_company)
    TextView tx_company;
    @Bind(R.id.tx_address)
    TextView txAddress;
    @Bind(R.id.edit_visitor_name)
    EditTextWithDel editVisitorName;
    @Bind(R.id.tx_sex_women)
    TextView txSexWomen;
    @Bind(R.id.tx_sex_man)
    TextView txSexMan;
    @Bind(R.id.switchBtn)
    SwitchButton switchBtn;
    @Bind(R.id.edit_visitor_car_num)
    EditTextWithDel editVisitorCarNum;
    @Bind(R.id.rela_carNum)
    RelativeLayout relaCarNum;
    @Bind(R.id.tx_arriveTime)
    TextMoreLayout tx_arriveTime;
    @Bind(R.id.rela_layout)
    RelativeLayout rela_layout;

    private int sexType=1;//1 男 2：女

    private int position=0;

    private NumberPickerDialog numberPickerDialog;

    private String userName;
    private String userTel;

    private String enterPriseId;

    @Override
    protected int getLayoutId() {
        return R.layout.visitor_add_activity;
    }

    @Override
    protected void init() {
        String subId=getIntent().getStringExtra("subId");
        StyleUtil.titleBackKeyWithRightTextViewListener(this, getIntent().getStringExtra("title"), "访客记录", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(VisitorAddActivity.this,VisitorHistoryActivity.class));
            }
        });
        Utils.editInputToLarge(editVisitorCarNum);
        switchBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    relaCarNum.setVisibility(View.VISIBLE);
                    openKeybord();
                    editVisitorCarNum.requestFocus();
                }else {
                    editVisitorCarNum.setText("");
                    closeKeyboard();
                    relaCarNum.setVisibility(View.GONE);
                }
            }
        });
        ServeStopTime serveStopTime = new ServeStopTime(this);
        serveStopTime.init(subId);
        tx_arriveTime.setRightText(Utils.getNowDate());

        Utils.setFilterNoNumber(editVisitorName);
        setUserAddress();
    }

    /**
     * 注意此处获取缓存数据，放置在页面上
     */
    private void setUserAddress(){
        User user = DataCacheManager.getInstance().getUser();
        userName= user.getUserName();
        userTel= user.getMobileNum();
        txUserName.setText(userName);
        txUserTel.setText(userTel);
        txAddress.setText(user.getEnterpriseAddress());
        tx_company.setText(user.getEnterpriseName());
        enterPriseId=user.getEnterpriseId();
    }
    /**
     * 新增需求，在访客记录，点击再次生成，将数据带入该页面(头部地址和用户信息不带入)
     * @param intent 传入的intent
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        VisitorEwmBean.DataBean dataBean=(VisitorEwmBean.DataBean)intent.getSerializableExtra("visitorEwmBean");
        if(dataBean==null)return;
        editVisitorName.setText(dataBean.getSurname());//访客姓名
        sexType=dataBean.getGender();
        onSexType();
        if(TextUtils.isEmpty(dataBean.getPlateNumber())){
            switchBtn.setChecked(false);
            editVisitorCarNum.setText("");
        }else {
            switchBtn.setChecked(true);
            editVisitorCarNum.setText(dataBean.getPlateNumber());
            if(!TextUtils.isEmpty(editVisitorCarNum.getText().toString())){
                editVisitorCarNum.setSelection(editVisitorCarNum.getText().toString().length());
            }
        }
        tx_arriveTime.setRightText(Utils.getNowDate());
        position=0;
//        txUserName.setText(dataBean.getOwnerName());
//        txUserTel.setText(dataBean.getOwnerPhone());
//        txAddress.setText(dataBean.getOwnerAddress());
//        tx_company.setText(dataBean.getEnterpriseName());
//        enterPriseId=dataBean.getEnterpriseId();
    }

    @OnClick({ R.id.tx_sex_women, R.id.tx_sex_man, R.id.tx_addCard,  R.id.tx_arriveTime})
    public void onClick(View view) {
        if(Utils.isFastDoubleClick())
            return;
        switch (view.getId()) {
            case R.id.tx_sex_women:
                sexType=2;
                onSexType();
                break;
            case R.id.tx_sex_man:
                sexType=1;
                onSexType();
                break;
            case R.id.tx_addCard:
                createQCode();
                break;
            case R.id.tx_arriveTime:
                numberPickerDialog=NumberPickerDialog.getNumberPickerDialog(position,Utils.getWeekDates());
                numberPickerDialog.show(getSupportFragmentManager(),"number");
                break;
        }
    }

    /**
     *sex 变化
     */
    private void onSexType(){
        if(sexType==1){
            txSexWomen.setTextColor(ContextCompat.getColor(this, R.color.font_color_gray));
            txSexWomen.setBackgroundResource(R.drawable.bg_cancel_white_black);
            txSexMan.setTextColor(ContextCompat.getColor(this, R.color.font_color_black));
            txSexMan.setBackgroundResource(R.drawable.bg_cancel_theme);
        }else {
            txSexWomen.setTextColor(ContextCompat.getColor(this, R.color.font_color_black));
            txSexWomen.setBackgroundResource(R.drawable.bg_cancel_theme);
            txSexMan.setTextColor(ContextCompat.getColor(this, R.color.font_color_gray));
            txSexMan.setBackgroundResource(R.drawable.bg_cancel_white_black);
        }
    }

    @Override
    public void onClick(int position) {
        numberPickerDialog.dismiss();
        this.position=position;
        tx_arriveTime.setRightText(Utils.getWeekDates()[position]);
    }

    /**
     * 生成访客通行二维码
     */
    private void createQCode(){
        String visitorName=editVisitorName.getText().toString().trim();
        String carNum=editVisitorCarNum.getText().toString().trim();
        if(TextUtils.isEmpty(visitorName)){
            ToastUtil.showShort(this,"请输入2-8位访客姓名");
            return;
        }
        if(visitorName.length()<2){
            ToastUtil.showShort(this,"访客姓名请使用2-8位中英文");
            return;
        }
        if(switchBtn.isChecked()&&!TextUtils.isEmpty(carNum)){
            if(carNum.length()<7)
            {
                ToastUtil.showShort(this,"请填写正确的车牌号");
                return;
            }
        }
        showLoading();
        Map<String, String> map = new HashMap<>();
        map.put("enterpriseId",enterPriseId);
        map.put("enterpriseName", tx_company.getText().toString());
        map.put("gender", String.valueOf(sexType));
        map.put("hasCar", switchBtn.isChecked()?"2":"1");//登记类型：1人行2车行
        map.put("ownerAddress",txUserName.getText().toString());
        map.put("ownerName", userName);
        map.put("ownerPhone", userTel);
        if (!TextUtils.isEmpty(carNum)&&switchBtn.isChecked())
            map.put("plateNumber", carNum);
        map.put("scheduleAt", Utils.getWeekDates()[position]);
        map.put("surname", visitorName);
        enqueue(createCallService(ServiceService.class).createVisitorEwm(map), new RetrofitCallbackListener<VisitorEwmBean>() {
            @Override
            public void onSuccess(Call<VisitorEwmBean> call, VisitorEwmBean result) {
                misLoading();
            }

            @Override
            public void onError(String msg) {
                misLoading();
                ToastUtil.show(msg);
            }
        });
    }
}
